package com.module.pubpage.ui.choiceCity

import android.content.Context
import android.os.Handler
import android.text.TextUtils
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.common.app.adapter.choiceArea.AreaGridListAdapter
import com.common.app.adapter.choiceArea.InnerListener
import com.common.app.adapter.decoration.GridItemDecoration
import com.common.app.data.bean.LocateState
import com.common.app.data.bean.BaseCityModel
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.ViewUtils
import com.module.pubpage.R


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：21/2/2023
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class CityListAdapter : RecyclerView.Adapter<CityListAdapter.BaseViewHolder> {
    private var mContext: Context
    private var mData: MutableList<BaseCityModel>? = ArrayList()
    private var mHistoryData: MutableList<BaseCityModel> = ArrayList()
    private var mHotData: MutableList<BaseCityModel>
    private var locateState = 0
    private var mInnerListener: InnerListener? = null
    private var mLayoutManager: LinearLayoutManager? = null
    private var stateChanged = false
    private var autoLocate = false
    private var mHotAdapter: AreaGridListAdapter? = null
    private var mHistoryAdapter: AreaGridListAdapter? = null

    private var showCode = false

    constructor(
        context: Context,
        data: MutableList<BaseCityModel>?,
        hotData: MutableList<BaseCityModel>,
        state: Int
    ) {
        mData = data
        mContext = context
        mHotData = hotData
        locateState = state
    }

    constructor(
        context: Context,
        data: MutableList<BaseCityModel>?,
        hotData: MutableList<BaseCityModel>,
        mHistoryData: MutableList<BaseCityModel>,
        showCode:Boolean = true
    ) {
        mData = data
        mContext = context
        mHotData = hotData
        this.mHistoryData = mHistoryData
        this.showCode = showCode
    }

    fun autoLocate(auto: Boolean) {
        autoLocate = auto
    }

    fun setLayoutManager(manager: LinearLayoutManager?) {
        mLayoutManager = manager
    }

    fun updateData(data: MutableList<BaseCityModel>?) {
        mData = data
        notifyDataSetChanged()
    }

    fun updateLocateState(location: BaseCityModel, state: Int) {
        mData?.removeAt(0)
        mData?.add(0, location)
        stateChanged = locateState != state
        locateState = state
        refreshLocationItem()
    }

    fun refreshLocationItem() {
        //如果定位城市的item可见则进行刷新
        if (stateChanged && mLayoutManager?.findFirstVisibleItemPosition() == 0) {
            stateChanged = false
            notifyItemChanged(0)
        }
    }

    fun updateHotData(tempList: MutableList<BaseCityModel>?) {
        mHotData.clear()
        tempList?.let {
            mHotData.addAll(it)
        }
        mHotAdapter?.notifyDataSetChanged()
        //        notifyDataSetChanged();
//        mData.remove(0);
//        mData.add(0, location);
//        stateChanged = !(locateState == state);
//        locateState = state;
//        refreshLocationItem();
    }

    /**
     * 滚动RecyclerView到索引位置
     *
     * @param index
     */
    fun scrollToSection(index: String?) {
        mData.isNullOrEmpty().yes {
            return
        }
        if (TextUtils.isEmpty(index)) return
        val size = mData?.size ?: 0
        for (i in 0 until size) {
            if (TextUtils.equals(
                    index?.substring(0, 1),
                    mData?.get(i)?.getSection()?.substring(0, 1)
                )
            ) {
                if (mLayoutManager != null) {
                    mLayoutManager?.scrollToPositionWithOffset(i, 0)
                    if (TextUtils.equals(index?.substring(0, 1), "定")) {
                        //防止滚动时进行刷新
                        Handler().postDelayed({ if (stateChanged) notifyItemChanged(0) }, 1000)
                    }
                    return
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val view: View
        return when (viewType) {
            VIEW_TYPE_LOCATION -> {
                view = LayoutInflater.from(mContext)
                    .inflate(R.layout.pubpage_cp_list_item_location_layout, parent, false)
                LocationViewHolder(view)
            }
            VIEW_TYPE_HISTORY -> {
                view = LayoutInflater.from(mContext)
                    .inflate(R.layout.pubpage_cp_list_item_hot_layout, parent, false)
                HistoryViewHolder(view)
            }
            VIEW_TYPE_HOT -> {
                view = LayoutInflater.from(mContext)
                    .inflate(R.layout.pubpage_cp_list_item_hot_layout, parent, false)
                HotViewHolder(view)
            }
            else -> {
                view = LayoutInflater.from(mContext)
                    .inflate(R.layout.pubpage_cp_list_item_default_layout, parent, false)
                DefaultViewHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        if (holder is DefaultViewHolder) {

            val pos = holder.getAdapterPosition()
            val data: BaseCityModel = mData?.get(pos) ?: return
            holder.name.text = data.name
            showCode.yes {
                data.code.isEmpty().yes {
                    holder.name.visibility = GONE
                }.otherwise {
                    var mName: String? = data.code
                    mName?.contains("+")?.no {
                        mName = "+$mName"
                    }
                    holder.mCode.text = mName
                    holder.name.visibility = VISIBLE
                }
            }
            holder.itemView.setOnClickListener(View.OnClickListener { v ->
                // 防止多次点击
                if (ViewUtils.isFastClick()) return@OnClickListener

                mInnerListener?.itemLocationClick(pos, data)
            })
        }
        //定位城市
        if (holder is LocationViewHolder) {
            val pos = holder.getAdapterPosition()
            val data: BaseCityModel = mData?.get(pos) ?: return
            //设置宽高
            val dm = mContext.resources.displayMetrics
            val screenWidth = dm.widthPixels
            val typedValue = TypedValue()
            val space = mContext.resources.getDimensionPixelSize(R.dimen.dp_16)
            val padding = mContext.resources.getDimensionPixelSize(R.dimen.dp_16)
            val indexBarWidth = mContext.resources.getDimensionPixelSize(R.dimen.dp_36)
            val itemWidth: Int =
                (screenWidth - padding - space * (AreaGridListAdapter.SPAN_COUNT - 1) - indexBarWidth) / AreaGridListAdapter.SPAN_COUNT
            val lp = holder.container.layoutParams
            lp.width = itemWidth
            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT
            holder.container.layoutParams = lp
            when (locateState) {
                LocateState.LOCATING -> holder.current.setText(R.string.common_cp_locating)
                LocateState.SUCCESS -> holder.current.text = data.name
                LocateState.FAILURE -> holder.current.setText(R.string.common_cp_locate_failed)
            }
            holder.container.setOnClickListener(View.OnClickListener { v -> //防止多次点击

                // 防止多次点击
                if (ViewUtils.isFastClick()) return@OnClickListener

                if (locateState == LocateState.SUCCESS) {
                    mInnerListener?.itemLocationClick(pos, data)
                } else if (locateState == LocateState.FAILURE) {
                    locateState = LocateState.LOCATING
                    notifyItemChanged(0)
                    mInnerListener?.locate()
                } else {
                    mInnerListener?.locate()
                }
            })
            //            //第一次弹窗，如果未定位则自动定位
//            if (autoLocate && locateState == LocateState.LOCATING && mInnerListener != null) {
//                mInnerListener.locate();
//                autoLocate = false;
//            }
        }
        //历史搜索
        if (holder is HistoryViewHolder) {
            val pos = holder.getAdapterPosition()
            mData?.get(pos) ?: return
            mHistoryAdapter = AreaGridListAdapter(mContext, mHistoryData)
            mHistoryAdapter?.setInnerListener(mInnerListener)
            holder.mRecyclerView.adapter = mHistoryAdapter
        }
        //热门城市
        if (holder is HotViewHolder) {
            val pos = holder.getAdapterPosition()
            mData?.get(pos) ?: return
            mHotAdapter = AreaGridListAdapter(mContext, mHotData)
            mHotAdapter?.setInnerListener(mInnerListener)
            holder.mRecyclerView.adapter = mHotAdapter
        }
    }

    override fun getItemCount(): Int {
        return mData?.size ?: 0
    }

    override fun getItemViewType(position: Int): Int {
//        if (position == 0 && TextUtils.equals("定", mData.get(position).getSection().substring(0, 1)))
        if (TextUtils.equals(
                "定",
                mData?.get(position)?.getSection()?.substring(0, 1)
            )
        ) return VIEW_TYPE_LOCATION
        //        if (position == 1 && TextUtils.equals("热", mData.get(position).getSection().substring(0, 1)))
        if (TextUtils.equals(
                "历",
                mData?.get(position)?.getSection()?.substring(0, 1)
            )
        ) return VIEW_TYPE_HISTORY
        return if (TextUtils.equals(
                "热",
                mData?.get(position)?.getSection()?.substring(0, 1)
            )
        ) VIEW_TYPE_HOT else super.getItemViewType(position)
    }

    fun setInnerListener(listener: InnerListener?) {
        mInnerListener = listener
    }

    open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(
        itemView
    )

    class DefaultViewHolder internal constructor(itemView: View) :
        BaseViewHolder(itemView) {
        var name: TextView
        var mCode: TextView

        init {
            name = itemView.findViewById(R.id.cp_list_item_name)
            mCode = itemView.findViewById(R.id.cp_list_item_code)
        }
    }

    class HotViewHolder internal constructor(itemView: View) : BaseViewHolder(itemView) {
        var mRecyclerView: RecyclerView

        init {
            mRecyclerView = itemView.findViewById(R.id.cp_hot_list)
            mRecyclerView.setHasFixedSize(true)
            mRecyclerView.layoutManager = GridLayoutManager(
                itemView.context,
                AreaGridListAdapter.SPAN_COUNT, LinearLayoutManager.VERTICAL, false
            )
            val space = itemView.context.resources.getDimensionPixelSize(R.dimen.dp_10)
            mRecyclerView.addItemDecoration(
                GridItemDecoration(
                    AreaGridListAdapter.SPAN_COUNT,
                    space
                )
            )
        }
    }

    class HistoryViewHolder internal constructor(itemView: View) :
        BaseViewHolder(itemView) {
        var mRecyclerView: RecyclerView

        init {
            mRecyclerView = itemView.findViewById(R.id.cp_hot_list)
            mRecyclerView.setHasFixedSize(true)
            mRecyclerView.layoutManager = GridLayoutManager(
                itemView.context,
                AreaGridListAdapter.SPAN_COUNT, LinearLayoutManager.VERTICAL, false
            )
            val space = itemView.context.resources.getDimensionPixelSize(R.dimen.dp_10)
            mRecyclerView.addItemDecoration(
                GridItemDecoration(
                    AreaGridListAdapter.SPAN_COUNT,
                    space
                )
            )
        }
    }

    class LocationViewHolder internal constructor(itemView: View) :
        BaseViewHolder(itemView) {
        var container: FrameLayout
        var current: TextView

        init {
            container = itemView.findViewById(R.id.cp_list_item_location_layout)
            current = itemView.findViewById(R.id.cp_list_item_location)
        }
    }

    companion object {
        private const val VIEW_TYPE_LOCATION = 10
        private const val VIEW_TYPE_HOT = 11
        private const val VIEW_TYPE_HISTORY = 12
    }
}